package pannel.product;

import system.BasePage;
import pannel.user.User;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.SQLException;
import java.util.*;
import java.util.List;

public class ProductManagementPage extends BasePage {
    private DefaultTableModel model;
    private List<Product> productList = new ArrayList<>();
    private JTable table;
    private JTextField searchField;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private ProductDao productDao;
    private int totalRecords = 0;

    public ProductManagementPage(User user) {
        super(user);
        productDao = new ProductDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("商品管理");
        setupContent();
        refreshTable();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("商品名称："));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolBar.setBackground(Color.WHITE);

        JButton addButton = new JButton("新增商品");
        JButton deleteButton = new JButton("删除商品");
        JButton editButton = new JButton("编辑商品");

        toolBar.add(addButton);
        toolBar.add(deleteButton);
        toolBar.add(editButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(toolBar, BorderLayout.CENTER);

        // 表格设置
        String[] columnNames = {"图片", "ID", "商品名称", "价格", "库存"};
        model = new NonEditableTableModel(new Object[0][], columnNames);
        table = new JTable(model);

        // 表格渲染设置
        setupTableRenderer();

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件处理
        setupButtonListeners(searchButton, addButton, deleteButton, editButton, prevButton, nextButton);

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    private void setupTableRenderer() {
        table.getTableHeader().setReorderingAllowed(false);
        TableColumn imageColumn = table.getColumnModel().getColumn(0);
        imageColumn.setCellRenderer(new ImageRenderer());
        imageColumn.setPreferredWidth(50);
        table.setRowHeight(45);
        
        // 设置其他列的宽度
        table.getColumnModel().getColumn(1).setPreferredWidth(50);  // ID
        table.getColumnModel().getColumn(2).setPreferredWidth(150); // 名称
        table.getColumnModel().getColumn(3).setPreferredWidth(80);  // 价格
        table.getColumnModel().getColumn(4).setPreferredWidth(80);  // 库存
    }

    private void setupButtonListeners(JButton searchButton, JButton addButton, 
            JButton deleteButton, JButton editButton, JButton prevButton, JButton nextButton) {
        
        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshTable();
        });

        addButton.addActionListener(e -> {
            ProductDialog dialog = new ProductDialog(null, "新增商品", null);
            if (dialog.showDialog()) {
                try {
                    Product newProduct = Product.builder()
                            .name(dialog.getProductName())
                            .price(dialog.getPrice())
                            .stock(dialog.getStock())
                            .imagePath(dialog.getImagePath())
                            .build();

                    if (productDao.insert(newProduct)) {
                        JOptionPane.showMessageDialog(this, "添加商品成功！");
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "添加商品失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "添加商品失败：" + ex.getMessage());
                }
            }
        });

        deleteButton.addActionListener(e -> handleDelete());
        editButton.addActionListener(e -> handleEdit());
        
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshTable();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshTable();
            }
        });
    }

    private void handleDelete() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int id = (Integer) table.getValueAt(selectedRow, 1);
            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要删除该商品吗？", "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try {
                    if (productDao.deleteById(id)) {
                        JOptionPane.showMessageDialog(this, "删除成功！");
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "删除失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "删除失败：" + ex.getMessage());
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的商品");
        }
    }

    private void handleEdit() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            Product selectedProduct = productList.get(selectedRow);
            ProductDialog dialog = new ProductDialog(null, "编辑商品", selectedProduct);
            if (dialog.showDialog()) {
                try {
                    selectedProduct.setName(dialog.getProductName());
                    selectedProduct.setPrice(dialog.getPrice());
                    selectedProduct.setStock(dialog.getStock());
                    selectedProduct.setImagePath(dialog.getImagePath());

                    if (productDao.updateById(selectedProduct)) {
                        JOptionPane.showMessageDialog(this, "更新成功！");
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "更新失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "更新失败：" + ex.getMessage());
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要编辑的商品");
        }
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                String searchText = searchField.getText().trim();
                productList = productDao.pageQuery(searchText, currentPage, pageSize);
                totalRecords = productDao.getTotalCount(searchText);

                model.setRowCount(0);
                for (Product product : productList) {
                    model.addRow(new Object[]{
                            createScaledImageIcon(product.getImagePath()),
                            product.getId(),
                            product.getName(),
                            product.getPrice(),
                            product.getStock()
                    });
                }
                updatePageInfo();
                table.repaint();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取商品数据失败：" + e.getMessage());
            }
        });
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }

    // 其他辅助类和方法与UserManagementPage类似，需要适当修改
    private static class NonEditableTableModel extends DefaultTableModel {
        public NonEditableTableModel(Object[][] data, Object[] columnNames) {
            super(data, columnNames);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 0) return ImageIcon.class;
            return super.getColumnClass(columnIndex);
        }
    }

    private static class ImageRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                     boolean isSelected, boolean hasFocus,
                                                     int row, int column) {
            if (value instanceof ImageIcon) {
                JLabel label = new JLabel((ImageIcon) value);
                label.setHorizontalAlignment(JLabel.CENTER);
                if (isSelected) {
                    label.setBackground(table.getSelectionBackground());
                    label.setOpaque(true);
                } else {
                    label.setOpaque(false);
                }
                return label;
            }
            return super.getTableCellRendererComponent(table, value, isSelected,
                    hasFocus, row, column);
        }
    }

    private static ImageIcon createScaledImageIcon(String path) {
        try {
            File imageFile = new File(path);
            if (!imageFile.exists() || !imageFile.isFile()) {
                throw new Exception("Image file does not exist: " + path);
            }

            ImageIcon originalIcon = new ImageIcon(path);
            if (originalIcon.getIconWidth() == -1) {
                throw new Exception("Invalid image file");
            }

            Image image = originalIcon.getImage();
            Image scaledImage = image.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
            return new ImageIcon(scaledImage);
        } catch (Exception e) {
            return createDefaultIcon();
        }
    }

    private static ImageIcon createDefaultIcon() {
        BufferedImage defaultImage = new BufferedImage(40, 40, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = defaultImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillOval(0, 0, 39, 39);
        g2d.setColor(Color.GRAY);
        g2d.drawOval(0, 0, 39, 39);
        g2d.dispose();
        return new ImageIcon(defaultImage);
    }
} 